package com.sugar.FileListener.service;

import com.sugar.FileListener.config.FileWatcherProperties;
import com.sugar.FileListener.listener.FileWatchEventListener;
import org.apache.commons.io.monitor.*;
import java.io.File;
import java.util.List;

/**
 * @author felix
 * @date 2025/7/3 15:10
 */
public class FileWatcherService {

    private final FileAlterationMonitor monitor;

    public FileWatcherService(FileWatcherProperties props, FileWatchEventListener listener) {
        File directory = new File(props.getPath());
        List<String> suffixes = props.getSuffixes();

        FileAlterationObserver observer = new FileAlterationObserver(directory);
        observer.addListener(new FileAlterationListenerAdaptor() {
            @Override
            public void onFileCreate(File file) {
                if (accept(file, suffixes)) listener.onCreate(file);
            }

            @Override
            public void onFileChange(File file) {
                if (accept(file, suffixes)) listener.onModify(file);
            }

            @Override
            public void onFileDelete(File file) {
                if (accept(file, suffixes)) listener.onDelete(file);
            }
        });

        this.monitor = new FileAlterationMonitor(props.getInterval(), observer);
    }

    private boolean accept(File file, List<String> suffixes) {
        if (suffixes == null || suffixes.isEmpty()) return true;
        return suffixes.stream().anyMatch(s -> file.getName().endsWith(s));
    }

    public void start() throws Exception {
        monitor.start();
    }

    public void stop() throws Exception {
        monitor.stop();
    }
}